package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.mall.commons.util.UserInfoUtil;
import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.constant.OrderConstants;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.form.OrderDetail;
import com.cskaoyan.order.form.PageResponse;
import com.cskaoyan.order.service.OrderCoreService;
import com.cskaoyan.order.service.OrderQueryService;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * 订单相关接口的 controller
 * 创建日期: 2022/04/22 16:27
 *
 * @author ChengWenqi
 */

@Slf4j
@RestController
@RequestMapping("shopping")
public class OrderController {

    @Autowired
    GlobalIdGeneratorUtil globalIdGeneratorUtil;

    @Autowired
    OrderCoreService orderCoreService;

    @Autowired
    OrderQueryService orderQueryService;


    /**
     * 创建订单
     * 创建日期：2022/04/22 16:20
     * @param  request
     * @param  servletRequest
     * @return com.cskaoyan.mall.commons.result.ResponseData
     * @author ChengWenqi
     */
    @PostMapping("order")
    public ResponseData createOrder(@RequestBody CreateOrderRequest request, HttpServletRequest servletRequest) {
        // 验证登录，获取用户id
        Long uid = UserInfoUtil.checkLoginAndGetUserId(servletRequest);
        request.setUserId(uid);
        // 用发号器生成 uniqueKey，赋值给 request
        String uniqueKey = globalIdGeneratorUtil.getNextSeq(OrderConstants.ORDER_UNIQUE_KEY, 1);
        request.setUniqueKey(uniqueKey);

        // 创建订单操作
        CreateOrderResponse response = orderCoreService.createOrder(request);
        // 创建订单成功
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            // todo:订单创建成功之后要发邮件
            return new ResponseUtil<String>().setData(response.getOrderId());
        }
        // 创建订单失败
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 获取当前登录用户的所有订单
     * 创建日期：2022/04/23 10:43
     * @param  request
     * @param  servletRequest
     * @return com.cskaoyan.mall.commons.result.ResponseData
     * @author ChengWenqi
     */
    @GetMapping("order")
    public ResponseData orderList(OrderListRequest request, HttpServletRequest servletRequest) {
        // 验证登录，获取用户id
        Long uid = UserInfoUtil.checkLoginAndGetUserId(servletRequest);
        request.setUserId(uid);
        // 查询
        OrderListResponse response = orderQueryService.orderList(request);
        // 获取订单列表成功
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            PageResponse pageResponse = new PageResponse();
            pageResponse.setData(response.getDetailInfoList());
            pageResponse.setTotal(response.getTotal());
            return new ResponseUtil<PageResponse>().setData(pageResponse);
        }
        // 获取订单列表失败
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }


    /**
     * 根据订单id，获取订单详情信息
     * 创建日期：2022/04/23 11:44
     * @param  orderId
     * @param  servletRequest
     * @return com.cskaoyan.mall.commons.result.ResponseData
     * @author ChengWenqi
     */
    @GetMapping("order/{id}")
    public ResponseData orderDetail(@PathVariable("id") String orderId, HttpServletRequest servletRequest) {
        // 验证用户是否登录
        UserInfoUtil.checkLoginAndGetUserId(servletRequest);

        OrderDetailRequest request = new OrderDetailRequest();
        request.setOrderId(orderId);
        // 查询
        OrderDetailResponse response = orderQueryService.orderDetail(request);
        // 成功
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            OrderDetail orderDetail = new OrderDetail();
            // 封装响应参数
            orderDetail.setUserName(response.getBuyerNick());
            orderDetail.setOrderTotal(response.getPayment());
            orderDetail.setUserId(response.getUserId());
            orderDetail.setGoodsList(response.getOrderItemDto());
            orderDetail.setTel(response.getOrderShippingDto().getReceiverMobile());
            orderDetail.setStreetName(response.getOrderShippingDto().getReceiverAddress());
            orderDetail.setOrderStatus(response.getStatus());
            return new ResponseUtil<OrderDetail>().setData(orderDetail);
        }
        // 失败
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }


    /**
     * 根据订单id，取消订单
     * 创建日期：2022/04/23 14:10
     * @param  request
     * @param  servletRequest
     * @return com.cskaoyan.mall.commons.result.ResponseData
     * @author ChengWenqi
     */
    @PostMapping("cancelOrder")
    public ResponseData cancelOrder(@RequestBody CancelOrderRequest request, HttpServletRequest servletRequest) {
        // 验证是否登录
        UserInfoUtil.checkLoginAndGetUserId(servletRequest);

        // 取消订单
        CancelOrderResponse response = orderCoreService.cancelOrder(request);
        // 成功
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<CancelOrderResponse>().setData(response);
        }
        // 失败
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    /**
     * 根据订单id，删除订单（同时删除订单商品关联记录和物流记录）（真删）
     * 创建日期：2022/04/23 15:53
     * @param  orderId
     * @param  servletRequest
     * @return com.cskaoyan.mall.commons.result.ResponseData
     * @author ChengWenqi
     */
    @DeleteMapping("order/{id}")
    public ResponseData deleteOrder(@PathVariable("id") String orderId, HttpServletRequest servletRequest) {
        // 验证用户是否登录
        UserInfoUtil.checkLoginAndGetUserId(servletRequest);

        DeleteOrderRequest request = new DeleteOrderRequest();
        request.setOrderId(orderId);
        // 删除订单
        DeleteOrderResponse response = orderCoreService.deleteOrder(request);
        // 删除成功
        if (OrderRetCode.SUCCESS.getCode().equals(response.getCode())) {
            return new ResponseUtil<DeleteOrderResponse>().setData(response);
        }
        // 失败
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

}
